package study.javabasic.Thread;

import java.util.concurrent.Semaphore;

/**
 *
 * @author zhangshuhan
 * @date 2019/2/28
 */
public class SemaphoreTest {
    public static void main(String[] args) {
        //10个工人
        int num = 10;
        //5台机器
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < num; i++) {
            new Thread(new TestSemaphore(i, semaphore)).start();
        }
    }
}


class TestSemaphore implements Runnable {

    private int num;

    private Semaphore semaphore;

    public TestSemaphore(int num, Semaphore semaphore) {
        this.num = num;
        this.semaphore = semaphore;
    }

    @Override
    public void run() {

        try {
            semaphore.acquire();
            System.out.println(num + "=====占用了一台机器");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(num + "======释放一台机器");
        semaphore.release();
    }
}